package com.qishanor.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qishanor.framework.base.DictVO;
import com.qishanor.framework.util.PasswordUtil;
import com.qishanor.framework.util.R;
import com.qishanor.system.model.*;
import com.qishanor.system.model.dto.SysUserInfoDto;
import com.qishanor.system.model.dto.SysUserDto;
import com.qishanor.system.service.SysRoleService;
import com.qishanor.system.service.SysUserRoleService;
import com.qishanor.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 周振林
 * @date: 2022-04-08
 * @Copyright: 博客：http://www.zhouzhenlin.com - 沉淀、分享、成长、让自己和他人都有所收获
 **/

@RestController
@RequestMapping("/api/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 获取用户字典
     */
    @GetMapping("/user_dict")
    public R getList()
    {
        List<DictVO> results=sysUserService.list(Wrappers.emptyWrapper())
                .stream().map(u->new DictVO<Integer>(u.getUsername(),u.getId().toString())).collect(Collectors.toList());
        return R.ok(results);
    }

    @GetMapping("/info")
    @SaCheckLogin
    public Object info(){
        SysUser user=sysUserService.getById(StpUtil.getLoginIdAsString());
        List<Integer> roleIds=sysUserRoleService.listObjs(Wrappers.lambdaQuery(SysUserRole.class)
                .select(SysUserRole::getRoleId).eq(SysUserRole::getUserId,user.getId()))
                .stream().map(u-> (int)u).collect(Collectors.toList());

        List<String> roleNames= sysRoleService.listObjs(Wrappers.lambdaQuery(SysRole.class)
                .select(SysRole::getName).in(SysRole::getId,roleIds)).stream().map(u->(String)u).collect(Collectors.toList());


        SysUserInfoDto vo=new SysUserInfoDto().setUserInfo(new SysUserInfoDto.InnerUser(user.getId(),user.getUsername(),user.getAvatar()))
                .setRoles(roleNames).setPermissions(StpUtil.getPermissionList());
        return R.ok(vo);
    }



    @GetMapping("/page")
    @SaCheckPermission("sys_user_view")
    public R page(Page page, SysUserDto sysUserDto){
        return R.ok(sysUserService.pageBy(page, sysUserDto));
    }

    @GetMapping("/{id}")
    public R getUser(@PathVariable Integer id){
        return  R.ok(sysUserService.getById(id));
    }

    @PostMapping
    @SaCheckPermission("sys_user_add")
    public R save(@RequestBody SysUserDto sysUserDto){
        return R.ok(sysUserService.saveUser(sysUserDto));
    }

    @PutMapping
    @SaCheckPermission("sys_user_edit")
    public R update(@RequestBody SysUserDto sysUserDto){
        return R.ok(sysUserService.updateUser(sysUserDto));
    }

    @DeleteMapping("/{id}")
    @SaCheckPermission("sys_user_del")
    public R removeById(@PathVariable Integer id){
        return  R.ok(sysUserService.removeById(id));
    }

    @PutMapping("/reset/{id}")
    public R resetPassword(@PathVariable Integer id){
        SysUser sysUser=sysUserService.getById(id);
        if(ObjectUtil.isEmpty(sysUser)){
            return  R.failed("用户不存在");
        }

        //重置为默认密码：123456
        String frontPassword=PasswordUtil.encryptFrontPassword("123456");
        String newPassword = SaSecureUtil.md5BySalt(frontPassword,"www.qishanor.com");
        sysUser.setPassword(newPassword);
        sysUserService.updateById(sysUser);
        return R.ok();
    }

}
